<template>
  <section class="todoapp">
    <TodoHeader  @add="addFn" />
    <TodoMain :list="isShow" @isDone="isDoneFn" @del="delFn" @selectAll="selectAll" />
    <TodoFooter v-show="list.length" :list="list" :type="type" @changeType="changeType" @clearAll="clearFn" />
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      type:'all',
      list: JSON.parse(localStorage.getItem('todo')) || [],
    }
  },
  methods: {
    addFn(keywords) {
      this.list.unshift({
        id:Date.now(),
        name: keywords,
        isDone:false
      })
    },
    isDoneFn(id){
      const obj = this.list.find(item => item.id === id)
      obj.isDone = !obj.isDone
    },
    delFn(id){
      this.list = this.list.filter(item => item.id !== id) 
    },
    changeType(type){
      this.type = type
    },
    clearFn(){
      this.list = this.list.filter(item => !item.isDone)
    },
    selectAll(val){
      this.list.forEach(item => item.isDone = val)
    }
  },
  computed:{
    isShow(){
      if(this.type === 'all'){
        return this.list
      } else if(this.type === 'active'){
        return this.list.filter(item => !item.isDone)
      } else {
        return this.list.filter(item => item.isDone)
      }
    },
  },
  watch:{
    list:{
      handler(){
        localStorage.setItem('todo',JSON.stringify(this.list))
      },
        deep:true
    }
  }
}
</script>

<style></style>
